<template>
  <div class="app-container">
    <div class="grouping cardBox">
      <div class="marginBottom">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16">
            <div class="left-panel">
              <el-button
                icon="el-icon-circle-plus-outline"
                type="primary"
                size="small"
                @click="goodsadd()"
                >添加核销员</el-button
              >
            </div>
          </el-col>
          <el-col :xs="24" :sm="8">
            <div class="right-panel el-button-group">
              <el-button
                class=""
                icon="el-icon-refresh"
                size="mini"
                @click="refresh"
              ></el-button>
              <el-dropdown trigger="click" :hide-on-click="false">
                <span class="el-dropdown-link">
                  <el-button
                    class=""
                    icon="el-icon-s-operation"
                    size="mini"
                  ></el-button>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="fruit in allTableThead" :key="fruit">
                    <el-checkbox v-model="checkboxTableThead" :label="fruit">{{
                      tableTheadOptions[fruit].label
                    }}</el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="20">
        <el-col>
          <el-table
            v-loading="loading"
            :data="tableData"
            :header-cell-style="{
              'background-color': '#f3f8fe',
              color: '#606266',
              height: '50px',
            }"
            style="width: 100%"
            row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            >
            <el-table-column
              v-for="fruit in tableThead"
              :key="fruit"
              :label="tableTheadOptions[fruit].label"
              align="center"
            >
              <template slot-scope="scope">
                <div v-if="fruit == 'status'">
                  <el-switch
                    @change="switchShowWay(scope.row)"
                    v-model="scope.row[status]"
                    :active-value="1"
                    :inactive-value="2"
                  >
                  </el-switch>
                </div>
                <div v-else>
                  {{ scope.row[fruit] }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              prop="address"
              label="操作"
              align="center"
              width="210px"
            >
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="editapplocation(scope.row)"
                >
                  编辑
                </el-button>
                <el-popconfirm
                  title="这是一段内容确定删除吗？"
                  @confirm="delGradeWay(scope.row)"
                >
                  <el-button
                    style="margin-left: 10px"
                    type="danger"
                    size="mini"
                    slot="reference"
                  >
                    删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table></el-col
        >
        <el-col class="marginTop marginBottom" style="text-align: right">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="searchForm.page"
            :limit.sync="searchForm.count"
            @pagination="getcatelist"
          />
        </el-col>
      </el-row>
    </div>
    <!-- add -->
    <el-dialog
      title="添加"
      :close-on-click-modal="false"
      :visible.sync="adddialogVisible"
      width="600px"
    >
      <el-row :gutter="20">
        <el-form ref="form" :rules="rules" :model="form" label-width="100px">
          <el-col :span="22">
            <el-form-item label="关联商户" prop="loc_pur_mer_id">
              <el-select
                style="width: 100%"
                v-model="form.loc_pur_mer_id"
                clearable
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethodUser"
                :loading="locPurMerIdLoading"
              >
                <el-option
                  v-for="item in locPurMerIdList"
                  :key="item.id"
                  :label="item.name + '(' + item.responsible_person + ')'"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="关联用户" prop="user_id">
              <el-input
                size="small"
                placeholder="请输入关联用户"
                v-model="form.user_id"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="22">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">禁用</el-radio>
                <el-radio :label="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取消</el-button>
        <el-button
          :loading="addPutLoading"
          type="primary"
          @click="submitForms('form')"
          >保存</el-button
        >
      </span>
    </el-dialog>
    <!--  -->
    <el-dialog
      title="编辑"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-row :gutter="20">
        <el-form ref="forms" :rules="ruless" :model="forms" label-width="100px">
          <el-col :span="22">
            <el-form-item label="名称" prop="name">
              <el-input
                size="small"
                placeholder="请输入类目名称"
                v-model="forms.name"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="forms.status">
                <el-radio :label="0">禁用</el-radio>
                <el-radio :label="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="排序" prop="sort">
              <el-input
                type="number"
                min="1"
                size="small"
                placeholder="请输入排序序号"
                v-model="forms.sort"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                placeholder="请输入..."
                v-model="forms.remark"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          :loading="addPutLoading"
          type="primary"
          @click="submitForm('forms')"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
  
  <script>
import LogoUpload from "@/components/FileUpload";
import {
  getLocalWriteOffList,
  addLocalWriteOff,
  editLocalWriteOff,
  delLocalWriteOff,
  getLocalWriteOffDetail,
  getMerchantList,
} from "@/api/groupbuying/index";
const tableTheadOption = {
  id: {
    label: "ID",
    field: "id",
  },
  created_at: {
    label: "创建时间",
    field: "created_at",
  },
  updated_at: {
    label: "更新时间",
    field: "updated_at",
  },
  loc_pur_mer_id: {
    label: "商户ID",
    field: "loc_pur_mer_id",
  },
  user_id: {
    label: "用户ID",
    field: "user_id",
  },
  user_name: {
    label: "用户名称",
    field: "user_name",
  },
  status: {
    label: "状态",
    field: "status",
  },
};

const allTableThead = [
  "created_at",
  "updated_at",
  "id",
  "loc_pur_mer_id",
  "user_id",
  "user_name",
  "status",
];
const defaultTableThead = ["created_at", "updated_at", "user_name", "status"];
export default {
  name: "application",
  components: { LogoUpload },
  data() {
    return {
      searchForm: {
        id: "",
        status: "",
        loc_pur_mer_id: "",
        user_name: "",
        name: "",
        page: 1,
        count: 10,
      },
      // 修改提交按钮加载
      addPutLoading: false,
      adddialogVisible: false,
      dialogVisible: false,

      rules: {
        name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              const req = /[^a-zA-Z\u4e00-\u9fa5]/g;
              console.log(req.test(value));
              if (value === "") {
                callback(new Error("请输入分类名称"));
              } else {
                if (req.test(value)) {
                  callback(new Error("分类名称只能包含中文和英文"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
      }, //表单验证
      ruless: {
        name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              const req = /[^a-zA-Z\u4e00-\u9fa5]/g;
              if (value === "") {
                callback(new Error("请输入分类名称"));
              } else {
                if (req.test(value)) {
                  callback(new Error("分类名称只能包含中文和英文"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        sort: [
          {
            required: true,
            validator: (rule, value, callback) => {
              const req = /\D/g;
              if (value === "") {
                callback(new Error("请输入排序序号"));
              } else {
                if (req.test(value)) {
                  callback(new Error("序号只能为整数"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
      }, //表单验证
      forms: {
        id: "",
        name: "",
        status: 1,
        sort: 1,
        remark: "",
      },
      form: {
        loc_pur_mer_id: "",
        user_id: "",
        user_name: "",
        status: 1,
      },
      locPurMerIdLoading: false,
      locPurMerIdList: [],
      tableData: [],
      total: 0,
      loading: true, //刷新
      tableKey: 1, // table key
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值
    };
  },
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(
        (i) => valArr.indexOf(i) >= 0
      );
      this.tableKey = this.tableKey + 1; // 为了保证table 每次都会重渲
    },
  },
  mounted() {
    getMerchantList({
      count: 20,
      page: 1,
    }).then((res) => {
      if (res.code !== 200 || res.status !== 1) {
        this.$messages.error(res.msg);
        rej();
      }
      this.locPurMerIdList = res.data.list;
      req();
    });
    this.getcatelist(); //类目列表
  },
  methods: {
    // 刷新
    refresh() {
      this.loading = true;
      this.getcatelist();
    },
    //类目列表
    getcatelist() {
      getLocalWriteOffList(this.searchForm).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    //编辑
    editapplocation(row) {
      var obj = JSON.parse(JSON.stringify(row));
      console.log(row);
      this.forms.id = obj.id;
      this.forms.pid = obj.pid;
      this.forms.name = obj.name;
      this.forms.status = obj.status;
      this.forms.sort = obj.sort;
      this.forms.remark = obj.remark;
      this.dialogVisible = true;
    },
    //添加
    goodsadd(row) {
      if (row) {
        this.form.pid = row.id;
      } else {
        this.form.pid = 0;
      }
      this.adddialogVisible = true;
    },
    // 根据搜索条件获取用户列表
    remoteMethodUser(query) {
      this.locPurMerIdLoading = true;
      getMerchantList({
        count: 20,
        page: 1,
      }).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.locPurMerIdLoading = false;
          return this.$messages.error(res.msg);
        }
        this.locPurMerIdLoading = false;
        this.locPurMerIdList = res.data.list;
      });
    },
    //编辑表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addPutLoading = true;
          editLocalWriteOff(this.forms)
            .then((res) => {
              if (res.code !== 200 || res.status !== 1) {
                this.addPutLoading = false;
                return this.$messages.error(res.msg);
              }

              this.forms = {
                id: "",
                pid: 0,
                name: "",
                status: 1,
                sort: 1,
                remark: "",
              };
              this.$refs.forms.resetFields();
              this.$messages.success("编辑成功");
              this.addPutLoading = false;
              this.dialogVisible = false;
              this.getcatelist();
            })
            .catch(() => {
              this.addPutLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    switchShowWay(val) {
      this.loading = true;
      var obj = {
        status: val.status,
        id: val.id,
      };
      editLocalWriteOff(val)
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.loading = false;
          this.$messages.success(res.msg);
          this.getListWay();
        })
        .catch((err) => {
          this.$messages.error(err.msg);
          this.loading = false;
          this.getListWay();
        });
    },
    //添加表单
    submitForms(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addPutLoading = true;
          addLocalWriteOff(this.form)
            .then((res) => {
              if (res.code !== 200 || res.status !== 1) {
                this.addPutLoading = false;
                return this.$messages.error(res.msg);
              }
              this.addPutLoading = false;
              this.$messages.success("添加成功");
              this.form = {
                pid: 0,
                name: "",
                status: 1,
                sort: 1,
                remark: "",
              };
              this.$refs.form.resetFields();
              this.adddialogVisible = false;
              this.getcatelist();
            })
            .catch(() => {
              this.addPutLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    //删除
    delGradeWay(row) {
      this.loading = true;
      delLocalWriteOff({ id: row.id }).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.loading = false;
          return this.$messages.error(res.msg);
        }
        this.$messages.success("删除成功");
        this.getcatelist();
      });
    },
  },
};
</script>
  
  <style lang="scss" scoped>
.title {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  font-size: 16px;
  line-height: 16px;
}

.sn {
  color: #606266;
  font-size: 13px;
}

.demo-table-expand {
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
  color: #515a6e;

  div {
    width: 30%;
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 12px;
  }
}

.marginTop {
  padding: 0 15px !important;
}
</style>
  